package com.juphoon.oauth.filter;

import com.juphoon.oauth.core.utils.CheckMobile;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author rongbin.huang
 * @create 2018-06-27 下午11:01
 **/
//@Component
@Deprecated
public class OauthTokenFilter extends OncePerRequestFilter {

    //@Autowired
    private RedisTemplate<String, String> redisTemplate;

   // @Autowired
    //@Qualifier("consumerTokenServices")
    ConsumerTokenServices consumerTokenServices;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        if ("/app/login".equals(request.getRequestURI())) {
            String username = request.getParameter("username");
            String userAgent = request.getHeader("USER-AGENT").toLowerCase();
            if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(userAgent)) {
                String token = redisTemplate.opsForValue().get(username + ":phone");
                if (token != null && CheckMobile.check(userAgent)) {
                    consumerTokenServices.revokeToken(token);
                }
                token = redisTemplate.opsForValue().get(username + ":pc");
                if (token != null && !CheckMobile.check(userAgent)) {
                    consumerTokenServices.revokeToken(token);
                }

            }

        }

        filterChain.doFilter(request, response);

    }


}
